/**
 * 智能提示指令
 */
import tem from './index.html'
class autocompleteCtrl {
  constructor($scope) {
      $scope.autocompleteArr ={
          id:[],
          name:[]
      }
      $scope.show = false
    
      $scope.getCity = function (newVal,name) {
          if(newVal){
              $.ajax({
                  type:'get',
                  url:'../../assets/json/cityjson.json',
                  async:false,
                  success:function(data){
                      data.find(function (value) {
                          if(value[name].indexOf(newVal) > -1){
                              if($scope.autocompleteArr[name].length > 0){
                                  if($scope.autocompleteArr[name].indexOf(value) < 0){
                                      $scope.autocompleteArr[name].push(value)
                                  }
                              } else {
                                  $scope.autocompleteArr[name].push(value)
                              }
                             
                          }
                      })
                  }
              })
          }
      }
      //初始化数据
      console.log('$scope.city', $scope.city)
      if($scope.city){
          $scope.getCity($scope.city,'id')
          $scope.autocomplete = $scope.autocompleteArr.id[0].name
      }
      $scope.$watch('autocomplete',function (newVal){
        $scope.autocompleteArr.id = []
        $scope.autocompleteArr.name = []
        if(newVal){
          $scope.getCity(newVal,'name')
        }

    })
      $scope.$watch('city',function (newVal){
        console.log('city.newVal', newVal)
        if(newVal){
            $scope.getCity(newVal,'id')
            $scope.autocomplete = $scope.autocompleteArr.id[0].name
        }
    },true)

      $scope.autocompleteClick = function (item) {
          $scope.autocomplete = item.name
          $scope.city = item.id
          $scope.autocompleteArr.id = []
          $scope.autocompleteArr.name = []
      }
  }
}

autocompleteCtrl.$inject = ['$scope']
module.exports = angular.module('directive.autocomplete', []).directive('autocomplete', function() {
    return {
        template: tem,
        replace:true,
        scope: {
            city: '='
        },
        controller: autocompleteCtrl
    }
}).name